package leihua.crm.workbench.web.controller;

import leihua.crm.commons.contants.Contants;
import leihua.crm.commons.domain.ReturnObject;
import leihua.crm.commons.utils.DateUtils;
import leihua.crm.commons.utils.UUIDUtils;
import leihua.crm.settings.domain.DicValue;
import leihua.crm.settings.domain.User;
import leihua.crm.settings.service.DicValueService;
import leihua.crm.settings.service.UserService;
import leihua.crm.workbench.domain.Activity;
import leihua.crm.workbench.domain.Clue;
import leihua.crm.workbench.domain.ClueActivityRelation;
import leihua.crm.workbench.domain.ClueRemark;
import leihua.crm.workbench.service.ActivityService;
import leihua.crm.workbench.service.ClueActivityRelationService;
import leihua.crm.workbench.service.ClueRemarkService;
import leihua.crm.workbench.service.ClueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author leiHua
 * @Date 2022/10/18 13:40
 */
@Controller
public class ClueController {
    @Autowired
    UserService userService;

    @Autowired
    DicValueService dicValueService;

    @Autowired
    ClueService clueService;

    @Autowired
    ActivityService activityService;

    @Autowired
    ClueRemarkService clueRemarkService;

    @Autowired
    ClueActivityRelationService clueActivityRelationService;

    //根据条件分页查询
    @RequestMapping("/workbench/clue/queryClueForPage.do")
    @ResponseBody
    public Object queryClueForPage(String fullname, String company, String owner, String phone,
                                   String source, String mphone, String state,String appellation,int pageNo,int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("fullname", fullname);
        map.put("company", company);
        map.put("owner", owner);
        map.put("phone", phone);
        map.put("source", source);
        map.put("mphone", mphone);
        map.put("state", state);
        map.put("appellation", appellation);
        int beginNo=(pageNo-1)*pageSize;
        map.put("beginNo",beginNo);
        map.put("pageSize",pageSize);
        Map<String, Object> resultMap = null;
        try {
            List<Clue> clueList = clueService.queryClueByConditionForPage(map);
            int totalRows = clueService.queryCountOfClueByCondition(map);
            resultMap = new HashMap<String, Object>();
            resultMap.put("clueList", clueList);
            resultMap.put("totalRows", totalRows);
            resultMap.put("code",'1');
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code",'0');
        }
        return resultMap;
    }

    //删除线索
    @RequestMapping("/workbench/clue/deleteClueByIds.do")
    @ResponseBody
    public Object deleteByIds(String[]id){
        ReturnObject returnObject = new ReturnObject();
        int i = clueService.deleteClueByids(id);
        try {
            if (i>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("删除成功");
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("删除失败");
            }
        } catch (Exception e) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("删除失败");
            e.printStackTrace();
        }
        return returnObject;
    }

    @RequestMapping("/workbench/clue/index.do")
    public String index(HttpServletRequest request) {
        List<User> userList = userService.queryAllUsers();
        List<DicValue> appellationList = dicValueService.queryDicValueByTypeCode("appellation");
        List<DicValue> clueStateList = dicValueService.queryDicValueByTypeCode("clueState");
        List<DicValue> sourceList = dicValueService.queryDicValueByTypeCode("source");
        request.setAttribute("userList", userList);
        request.setAttribute("appellationList", appellationList);
        request.setAttribute("clueStateList", clueStateList);
        request.setAttribute("sourceList", sourceList);
        return "workbench/clue/index";
    }

    @RequestMapping("/workbench/clue/saveCreateClue.do")
    @ResponseBody
    public Object saveCreateClue(Clue clue, HttpSession session) {
        ReturnObject returnObject = new ReturnObject();
        try {
            User user = (User) session.getAttribute(Contants.SESSION_USER);
            clue.setId(UUIDUtils.getUUID());
            clue.setCreateTime(DateUtils.formateDateTime(new Date()));
            clue.setCreateBy(user.getId());
            int i = clueService.saveCreateClue(clue);
            if (i > 0) {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("添加成功");
            } else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("添加失败，请联系管理员");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加失败，请联系管理员");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/clue/detailClue.do")
    public String detailClue(String id,HttpServletRequest request){
        //线索详情信息
        //线索备注信息
        //关联的市场活动信息
        Clue clue = clueService.queryClueForDetailById(id);
        List<ClueRemark> remarkList = clueRemarkService.queryClueRemarkForDetailByClueId(id);
        List<Activity> activityList = activityService.queryActivityForDetailByClueId(id);
        request.setAttribute("clue",clue);
        request.setAttribute("remarkList",remarkList);
        request.setAttribute("activityList",activityList);

        return "workbench/clue/detail";
    }

    @RequestMapping("/workbench/clue/queryActivityForDetailByActivityNameAndClueId.do")
    @ResponseBody
    public Object queryActivityForDetailByActivityNameAndClueId(String activityName,String clueId){
        Map<String,Object> map=new HashMap<>();
        map.put("activityName",activityName);
        map.put("clueId",clueId);
        List<Activity> activityList = activityService.queryActivityForDetailByActivityNameAndClueId(map);

        return activityList;
    }

    //线索关联市场活动信息
    @RequestMapping("/workbench/clue/saveBund.do")
    @ResponseBody
    public Object saveBund(String []activityId,String clueId){
        ReturnObject returnObject = new ReturnObject();
        List<ClueActivityRelation> relationList=new ArrayList<>();
        ClueActivityRelation clueActivityRelation=null;
        for (String id : activityId) {
            clueActivityRelation= new ClueActivityRelation();
            clueActivityRelation.setClueId(clueId);
            clueActivityRelation.setId(UUIDUtils.getUUID());
            clueActivityRelation.setActivityId(id);
            relationList.add(clueActivityRelation);
        }
        try {
            int i = clueActivityRelationService.saveCreateClueActivityRelationByList(relationList);
            if (i>0){   //插入 关系信息成功后
                //查询与线索相关联的 市场活动
                List<Activity> activityList = activityService.queryActivityForDetailByClueId(clueId);
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(activityList);  //返回该线索相关联的  市场活动  ，用于刷新前端页面
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("关联失败，请联系管理员");
            }

        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("关联失败，请联系管理员");
        }

        return returnObject;
    }

    //删除线索绑定
    @RequestMapping("/workbench/clue/deleteBund.do")
    @ResponseBody
    public Object deleteBund(ClueActivityRelation clueActivityRelation){
        ReturnObject returnObject = new ReturnObject();
        try {
            int i = clueActivityRelationService.deleteClueActivityRelationByActivityIdAndClueId(clueActivityRelation);
            if (i>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("删除失败，请联系管理员");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("删除失败，请联系管理员");
        }
        return returnObject;
    }

    //跳转到线索转换页面 (查询该线索的信息，和一个字典值)
    @RequestMapping("/workbench/clue/toConvert.do")
    public String toConvert(String clueId,HttpServletRequest request){
        //查询线索的明细信息
        Clue clue = clueService.queryClueForDetailById(clueId);
        List<DicValue> stageList = dicValueService.queryDicValueByTypeCode("stage");
        request.setAttribute("clue",clue);
        request.setAttribute("stageList",stageList);
        return "workbench/clue/convert";
    }

    //根据名称查询市场活动 （查询线索已经关联的）
    @RequestMapping("/workbench/clue/queryActivityForConvertByActivityNameAndClueId")
    @ResponseBody
    public Object queryActivityForConvertByActivityNameAndClueId(String clueId,String activityName){
        ReturnObject returnObject = new ReturnObject();
        Map<String,Object> map=new HashMap();
        map.put("clueId",clueId);
        map.put("activityName",activityName);
        List<Activity> activityList = activityService.queryActivityForConvertByActivityNameAndClueId(map);
        return activityList;
    }

    @RequestMapping("/workbench/clue/saveConvertClue")
    @ResponseBody
    public Object saveConvertClue(String clueId,String money,String name ,String expected_date,String stage,
                                  String activityId,String isCreateTran,HttpSession session){
        Map<String,Object> map=new HashMap<>();
        map.put("clueId",clueId);
        map.put("money",money);
        map.put("name",name);
        map.put("expected_date",expected_date);
        map.put("stage",stage);
        map.put("activityId",activityId);
        map.put("isCreateTran",isCreateTran);
        User user = (User) session.getAttribute(Contants.SESSION_USER);
        map.put(Contants.SESSION_USER,user);
        ReturnObject returnObject = new ReturnObject();
        try {
            clueService.saveConvertClue(map);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("转换失败，请联系管理员");
        }
        return returnObject;
    }

    //插入一条 备注信息
    @RequestMapping("/workbench/clue/insertClueRemark")
    @ResponseBody
    public Object insertClueRemark(String clueId,String noteContent,HttpSession session){
        ReturnObject returnObject = new ReturnObject();
        User user=(User) session.getAttribute(Contants.SESSION_USER);
        try {
            ClueRemark clueRemark = new ClueRemark();
            clueRemark.setId(UUIDUtils.getUUID());
            clueRemark.setNoteContent(noteContent);
            clueRemark.setCreateTime(DateUtils.formateDateTime(new Date()));
            clueRemark.setCreateBy(user.getId());
            clueRemark.setEditFlag(Contants.REMARK_DEIT_FLAG_NO_EDITED);
            clueRemark.setClueId(clueId);
            int i = clueRemarkService.saveClueRemark(clueRemark);
            if (i>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(clueRemark);
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("添加失败，请联系管理员");
            }
        } catch (Exception e) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加失败，请联系管理员");
            e.printStackTrace();
        }
        return returnObject;
    }

    //修改模态窗口显示的信息
    @RequestMapping("/workbench/clue/toEditClue.do")
    @ResponseBody
    public Object toEditClue(String clueId){
        Clue clue = clueService.queryClueByKey(clueId);
        return clue;
    }

    //保存修改
    @RequestMapping("/workbench/clue/editClue.do")
    @ResponseBody
    public Object editClue(Clue clue,HttpSession session){
        ReturnObject returnObject = new ReturnObject();
        try {
            User user=(User)session.getAttribute(Contants.SESSION_USER);
            clue.setEditBy(user.getId());
            clue.setEditTime(DateUtils.formateDateTime(new Date()));
            int i = clueService.editClueSelective(clue);

            if (i>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("修改失败，请联系管理员");
            }
        } catch (Exception e) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("修改失败，请联系管理员");
            e.printStackTrace();
        }
        return  returnObject;
    }


}
